import streamlit as st
import pandas as pd
from src.core.test_checker import check_test_cases
from src.core.config import get_assistant_config
from src.core.excel import generate_excel
from src.utils.image import get_base64_image

# 设置页面配置
st.set_page_config(
    page_title="测试用例优化",
    page_icon="../assets/header-logo.png",
    layout="wide",
    initial_sidebar_state="collapsed"
)

# 自定义CSS样式
st.markdown("""
<style>
    .main {
        max-width: 1200px;
        padding: 2rem;
    }
    /* 让进度条占满宽度 */
    .element-container, .stMarkdown, .stText {
        width: 100% !important;
        max-width: 100% !important;
    }
    /* 进度条容器样式 */
    .stProgress > div {
        width: 100% !important;
        max-width: 100% !important;
    }
    /* 代码块和JSON显示样式 */
    .stCodeBlock, pre {
        width: 100% !important;
        max-width: 100% !important;
    }
    /* 文本输出样式 */
    .fixed-width {
        font-family: monospace;
        white-space: pre-wrap;
        width: 100% !important;
        max-width: 100% !important;
    }
    /* 按钮样式 */
    .stButton>button {
        width: 100%;
        margin-top: 1rem;
    }
    .stProgress .st-bo {
        background-color: #00a0dc;
    }
    .stDataFrame {
        margin-top: 1rem;
    }
    .block-container {
        padding-top: 2rem;
        padding-bottom: 2rem;
        max-width: 100% !important;
    }
    h1 {
        color: #2c3e50;
        margin-bottom: 2rem;
    }
    h2 {
        color: #34495e;
        margin-top: 2rem;
    }
    .stAlert {
        margin-top: 1rem;
        width: 100% !important;
    }
    /* Expander 样式 */
    .streamlit-expanderHeader {
        width: 100% !important;
        max-width: 100% !important;
    }
    .streamlit-expanderContent {
        width: 100% !important;
        max-width: 100% !important;
        padding: 0 !important;
    }
    /* 添加标题图标样式 */
    .title-container {
        display: flex;
        flex-direction: column;  /* 整体垂直排列 */
        align-items: center;     /* 水平居中 */
        gap: 5px;               /* 行间距 */
        padding: 1rem 0;
        margin-bottom: 1.5rem;
    }
    
    /* 添加标题行容器 */
    .title-row {
        display: flex;          /* 水平排列 */
        align-items: center;    /* 垂直居中对齐 */
        gap: 10px;             /* 图标和标题间距 */
    }

    .title-icon {
        width: 40px;          /* 固定宽度 */
        height: auto;          /* 高度自动调整 */
        object-fit: contain;   /* 保持长宽比 */
    }

    .title-container h1 {
        font-size: 2rem;       /* 与首页保持一致 */
        color: #2c3e50;
        margin: 0;
    }
</style>
""", unsafe_allow_html=True)

def read_excel_to_json(file):
    """读取Excel文件并转换为JSON格式"""
    try:
        df = pd.read_excel(file)
        return df.to_dict('records')
    except Exception as e:
        st.error(f"Excel文件读取失败: {str(e)}")
        return None

def main():
    st.markdown("<h2 style='font-size: 24px;'>📤 Excel测试用例</h2>", unsafe_allow_html=True)
    
    # 文件上传
    uploaded_file = st.file_uploader(
        "上传测试用例",
        type=["xlsx"],
        help="请上传标准格式的Excel测试用例文件"
    )
    
    if uploaded_file:
        # 读取Excel
        test_cases = read_excel_to_json(uploaded_file)
        
        if test_cases:
            # 显示原始用例
            with st.expander("查看原始用例"):
                st.dataframe(pd.DataFrame(test_cases))
            
            # 执行优化
            if st.button("开始优化", use_container_width=True):
                with st.spinner("正在优化测试用例..."):
                    # 使用 TestCaseChecker 进行优化
                    checker_config = get_assistant_config('test_checker')
                    optimized_cases = check_test_cases(
                        test_cases, 
                        checker_config['api_key']
                    )
                    
                    # 显示优化结果
                    st.success("用例优化完成！")
                    st.dataframe(pd.DataFrame(optimized_cases))
                    
                    # 获取原始文件名，并添加 "_optimized" 后缀
                    original_filename = uploaded_file.name
                    optimized_filename = original_filename.rsplit('.', 1)[0] + "_optimized.xlsx"

                    # 导出优化后的用例
                    excel_data = generate_excel(optimized_cases)
                    st.download_button(
                        "⬇️ 下载优化后的用例",
                        data=excel_data,
                        file_name=optimized_filename,  # 使用修改后的文件名
                        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        use_container_width=True
                    )

# 标题区域
st.markdown("""
<div class="title-container">
    <div class="title-row">
        <img src="data:image/png;base64,{}" class="title-icon">
        <h1>测试用例优化</h1>
    </div>
</div>
""".format(get_base64_image("../assets/header-logo.png")), unsafe_allow_html=True)

if __name__ == "__main__":
    main() 